<template>
  <div class="organization-search-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <div class="header-title">搜索</div>
        <div class="cancel-btn" @click="goBack">取消</div>
      </div>

      <!-- 搜索框 -->
      <div class="search-container">
        <van-search
          autocomplete="off"
          v-model="searchValue"
          placeholder="搜索人员姓名或职位"
          shape="round"
          background="transparent"
          left-icon="search"
          @search="onSearch"
          @update:model-value="onInput"
          autofocus
        />
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-content">
      <!-- 加载状态 - 骨架屏 -->
      <div v-if="loading" class="search-skeleton">
        <van-skeleton :row="5" :loading="true" avatar />
      </div>

      <!-- 搜索提示 -->
      <div v-else-if="!searchValue" class="search-hint">
        <div class="hint-icon">
          <van-icon name="search" size="48" color="#c8c9cc" />
        </div>
        <div class="hint-text">输入关键词开始搜索</div>
      </div>

      <!-- 无搜索结果 -->
      <div v-else-if="searchValue && searchResults.length === 0 && !loading" class="empty-result">
        <div class="empty-icon">
          <van-icon name="search" size="48" color="#c8c9cc" />
        </div>
        <div class="empty-text">未找到相关人员</div>
      </div>

      <!-- 搜索结果列表 -->
      <div v-else class="result-list">
        <div
          v-for="member in searchResults"
          :key="member.id"
          class="member-item"
          @click="viewMemberDetail(member)"
        >
          <div class="member-avatar">
            <AvatarDisplay :url="member.url" :name="member.name" />
          </div>
          <div class="member-info">
            <div class="member-name">
              {{ member.name }}
              <span v-if="member.admin === 1" class="admin-tag">管理员</span>
              <!-- <span v-if="member.ceo === 1" class="ceo-tag">CEO</span>
              <span v-if="member.hr === 1" class="hr-tag">HR</span> -->
            </div>
            <div class="member-details">
              <span class="member-phone">{{ member.phone }}</span>
              <!-- <span v-if="member.position" class="member-position">{{ member.position }}</span> -->
            </div>
            <!-- <div v-if="member.department!=-1"  class="member-department">
              部门: {{  member.department }} 
            </div> -->
            <div v-if="member.position"  class="member-department">
              职位: {{  member.position }} 
            </div>
          </div>
          <van-icon name="arrow" class="arrow-icon" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { searchMembers, type SearchMember } from '@/api/organization'
import { getUserPicture } from '@/api/contract'
import { smartGoBack } from '@/utils/navigation';
import defaultAvatar from '@/assets/homeOther/picture.png'
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue'

// 路由实例
const router = useRouter()
const route = useRoute()

// 搜索值
const searchValue = ref('')

// 搜索结果
const searchResults = ref<SearchMemberWithAvatar[]>([])

// 加载状态
const loading = ref(false) // 初始为false，避免闪烁

// 搜索防抖定时器
let searchTimer: NodeJS.Timeout | null = null

// 扩展搜索成员类型，添加头像字段
interface SearchMemberWithAvatar extends SearchMember {
  avatar: string
  url: string // 添加url字段用于头像组件
}

// 获取用户头像
const getUserAvatar = async (url: string): Promise<string> => {
  if (!url || url.trim() === '') {
    return defaultAvatar
  }
  
  try {
    const avatarBlob = await getUserPicture(url)
    return URL.createObjectURL(avatarBlob)
  } catch (error) {
    console.error('获取用户头像失败:', error)
    return defaultAvatar
  }
}

// 执行搜索
const performSearch = async (keyword: string | any) => {
  // 确保keyword是字符串类型
  const searchKeyword = typeof keyword === 'string' ? keyword : String(keyword || '')
  
  if (!searchKeyword.trim()) {
    searchResults.value = []
    return
  }

  try {
    loading.value = true
    const response = await searchMembers(searchKeyword)
    
    if (response.code === 0) {
      // 处理搜索结果，获取头像
      const membersWithAvatars = await Promise.all(
        response.data.map(async (member: SearchMember) => {
          const avatar = await getUserAvatar(member.url)
          return {
            ...member,
            avatar: avatar,
            url: member.url // 保留原始url用于头像组件
          }
        })
      )
      
      searchResults.value = membersWithAvatars
      console.log('搜索结果:', response.data)
    } else {
      showToast(response.msg || '搜索失败')
      searchResults.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error)
    showToast('搜索失败，请稍后重试')
    searchResults.value = []
  } finally {
    loading.value = false
  }
}

// 搜索输入处理（防抖）
const onInput = (value: string) => {
  // 清除之前的定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  // 设置新的定时器，500ms后执行搜索
  searchTimer = setTimeout(() => {
    performSearch(value)
  }, 500)
}

// 搜索按钮点击处理
const onSearch = (value: string) => {
  // 清除防抖定时器
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  
  // 立即执行搜索
  performSearch(value)
}

// 返回上一页
const goBack = () => {
  smartGoBack(router)
}

// 查看成员详情
const viewMemberDetail = (member: SearchMemberWithAvatar) => {
  // showToast(`查看${member.name}的详情`)
  // 这里可以根据需要跳转到成员详情页面
   router.push(`/organization/edit-member/${member.id}`)
}

// 页面加载
onMounted(() => {
  // 如果有初始搜索关键词，执行搜索
  const initialKeyword = route.query.keyword as string
  if (initialKeyword) {
    searchValue.value = initialKeyword
    performSearch(initialKeyword)
  }
  
  console.log('组织架构搜索页面已加载')
})

// 监听路由变化
watch(() => route.query.keyword, (newKeyword) => {
  if (newKeyword && typeof newKeyword === 'string') {
    searchValue.value = newKeyword
    performSearch(newKeyword)
  }
})
</script>

<style lang="scss" scoped>
.organization-search-container {
  width: 100%;
  min-height: 100vh;
  background: #F2F2F6;
  overflow-x: hidden;
}

// 顶部导航区域背景
.header-wrapper {
  width: 750px;
  height: 284px;
  background: #3F99F9;
  border-radius: 0px 0px 0px 0px;
  position: relative;
  margin: 0 auto;
}

// 顶部导航
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 44px 40px 20px 20px;
  background: transparent;
  position: relative;

  .back-icon {
    width: 60px;
    height: 60px;
    font-size: 60px;
    color: #FFFFFF;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .header-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    width: 324px;
    height: 54px;
    font-family: 'Source Han Sans CN', 'Source Han Sans CN';
    font-weight: 500;
    font-size: 36px;
    color: #FFFFFF;
    text-align: center;
    font-style: normal;
    text-transform: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .cancel-btn {
    width: 60px;
    height: 60px;
    font-family: 'Source Han Sans CN', 'Source Han Sans CN';
    font-weight: 500;
    font-size: 28px;
    color: #FFFFFF;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

// 搜索框
.search-container {
  position: absolute;
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  width: 670px;
  height: 70px;
  background: #FFFFFF;
  border-radius: 10px 10px 10px 10px;
  display: flex;
  align-items: center;

  :deep(.van-search) {
    padding: 0;
    background: transparent;
    width: 100%;
    height: 100%;

    .van-search__content {
      background: transparent;
      border: none;
      border-radius: 0;
      height: 100%;
      display: flex;
      align-items: center;
      padding: 24px 0 23px 36px;

      // 解决不同分辨率下文字显示问题
      .van-cell--borderless {
        height: auto;
      }

      .van-search__field {
        height: auto;
      }

      .van-field__control {
        font-family: 'Source Han Sans CN', 'Source Han Sans CN';
        font-weight: 500;
        font-size: 28px;
        color: #333;
        text-align: left;
        font-style: normal;
        text-transform: none;
        background: transparent;
        border: none;
        height: auto;

        &::placeholder {
          font-family: 'Source Han Sans CN', 'Source Han Sans CN';
          font-weight: 500;
          font-size: 28px;
          color: #97999C;
          text-align: left;
          font-style: normal;
          text-transform: none;
        }
      }
    }

    .van-search__action {
      display: none;
    }

    .van-field__left-icon {
      width: 23px;
      height: 23px;
      background: transparent;
      border-radius: 0;
      margin-right: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      .van-icon {
        font-size: 28px;
        color: #97999C;
      }
    }
  }
}

// 搜索内容区域
.search-content {
  margin-top: 20px;
  
  // 加载状态样式
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 60px 0;
    font-size: 28px;
    color: #666;
  }
  
  // 搜索提示和空状态样式
  .search-hint, .empty-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 60vh;
    font-size: 28px;
    color: #666;
    
    .hint-icon, .empty-icon {
      margin-bottom: 16px;
    }
    
    .hint-text, .empty-text {
      font-size: 28px;
      color: #666;
    }
  }
  
  // 搜索结果列表
  .result-list {
    background: #fff;
    box-shadow: 0px 4px 15px 0px rgba(0, 0, 0, 0.05);
    padding-bottom: 20px;
    // 成员项
    .member-item {
      display: flex;
      align-items: center;
      padding: 21px 30px 0 40px;
      cursor: pointer;
      &:active {
        background-color: #f5f5f5;
      }

      .member-avatar {
        width: 76px;
        height: 76px;
        border-radius: 20px;
        margin-right: 17px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 20px;
        }
      }

      .member-info {
        flex: 1;

        .member-name {
          display: flex;
          align-items: center;
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 32px;
          color: #333333;
          letter-spacing: 1px;
          text-align: left;
          font-style: normal;
          text-transform: none;
          padding-bottom: 6px;

          .admin-tag, .ceo-tag, .hr-tag {
            color: #3FC43A;
            font-size: 20px;
            padding: 4px 8px;
            border-radius: 6px 6px 6px 6px;
            border: 1px solid #3FC43A;
            margin-left: 12px;
            font-weight: 400;
          }
          
          .ceo-tag {
            color: #ee0a24;
            border-color: #ee0a24;
          }
          
          .hr-tag {
            color: #07c160;
            border-color: #07c160;
          }
        }

        .member-details {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 22px;
          color: #999999;
          letter-spacing: 1px;
          text-align: left;
          font-style: normal;
          text-transform: none;
          
          .member-phone {
            margin-right: 12px;
          }
          
          .member-position {
            color: #999999;
          }
        }
        
        .member-department {
          font-family: Source Han Sans CN, Source Han Sans CN;
          font-weight: 400;
          font-size: 22px;
          color: #999999;
          letter-spacing: 1px;
          text-align: left;
          font-style: normal;
          text-transform: none;
          margin-top: 2px;
        }
      }

      .arrow-icon {
        width: 38px;
        height: 38px;
        font-size: 38px;
        color: #999;
      }
    }
  }
}

// 搜索骨架屏容器样式
.search-skeleton {
  padding: 40px;
}
</style>